package com.example.myjavafx;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TodoController {
    @FXML
    private TextField inputField;
    @FXML
    private ListView<TodoItem> todoList;

    private final ObservableList<TodoItem> items = FXCollections.observableArrayList();

    @FXML
    public void initialize() {
        todoList.setItems(items);
        loadFromFile(); // 启动时加载数据
    }

    @FXML
    private void handleAdd() {
        String text = inputField.getText().trim();
        if (!text.isEmpty()) {
            items.add(new TodoItem(text));
//            inputField.clear();
            saveToFile(); // 保存到文件
        }
    }

    // 文件存储与加载
    private void saveToFile() {
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("todo-list.txt"))) {
            for (TodoItem item : items) {
                writer.write(item.getDescription());
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadFromFile() {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get("todo-list.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                items.add(new TodoItem(line));
            }
        } catch (IOException e) {
            // 文件不存在时忽略
        }
    }
}
